"""
主应用入口

基于多智能体的量化投研系统的FastAPI应用入口。
"""

from fastapi import FastAPI, Request, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse
from contextlib import asynccontextmanager
import uvicorn
from typing import Dict, Any
import asyncio
import logging

from .config.settings import get_settings
from .config.database import init_database, close_database
from .config.redis_config import init_redis, close_redis
from .api import api_router
from .middleware import setup_middleware
from .dependencies import setup_dependencies


# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    应用生命周期管理
    
    Args:
        app: FastAPI应用实例
    """
    # 启动时初始化
    logger.info("正在启动量化投研系统...")
    
    try:
        # 初始化数据库
        await init_database()
        logger.info("数据库初始化完成")
        
        # 初始化Redis
        await init_redis()
        logger.info("Redis初始化完成")
        
        # 初始化智能体系统
        from .agents.agent_registry import AgentRegistry
        agent_registry = AgentRegistry()
        logger.info("🔍 检查AgentRegistry.initialize方法...")
        if hasattr(agent_registry, 'initialize'):
            logger.info("✅ AgentRegistry.initialize方法存在")
            await agent_registry.initialize()
        else:
            logger.error("❌ AgentRegistry.initialize方法不存在")
            logger.info(f"AgentRegistry可用方法: {[method for method in dir(agent_registry) if not method.startswith('_') and callable(getattr(agent_registry, method))]}")
        app.state.agent_registry = agent_registry
        logger.info("智能体系统初始化完成")
        
        # 初始化协调引擎
        from .coordination.coordination_engine import CoordinationEngine
        coordination_engine = CoordinationEngine(agent_registry)
        logger.info("🔍 检查CoordinationEngine.initialize方法...")
        if hasattr(coordination_engine, 'initialize'):
            logger.info("✅ CoordinationEngine.initialize方法存在")
            await coordination_engine.initialize()
        else:
            logger.error("❌ CoordinationEngine.initialize方法不存在")
            logger.info(f"CoordinationEngine可用方法: {[method for method in dir(coordination_engine) if not method.startswith('_') and callable(getattr(coordination_engine, method))]}")
        app.state.coordination_engine = coordination_engine
        logger.info("协调引擎初始化完成")
        
        # 初始化工作流管理器
        from .workflows.workflow_manager import WorkflowManager
        workflow_manager = WorkflowManager()
        logger.info("🔍 检查WorkflowManager.initialize方法...")
        if hasattr(workflow_manager, 'initialize'):
            logger.info("✅ WorkflowManager.initialize方法存在")
            await workflow_manager.initialize()
        else:
            logger.error("❌ WorkflowManager.initialize方法不存在")
            logger.info(f"WorkflowManager可用方法: {[method for method in dir(workflow_manager) if not method.startswith('_') and callable(getattr(workflow_manager, method))]}")
        app.state.workflow_manager = workflow_manager
        logger.info("工作流管理器初始化完成")
        
        # 初始化数据管理器
        from .data.data_manager import DataManager
        data_manager = DataManager()
        await data_manager.initialize()
        app.state.data_manager = data_manager
        logger.info("数据管理器初始化完成")
        
        logger.info("量化投研系统启动完成")
        
        yield
        
    except Exception as e:
        logger.error(f"系统启动失败: {e}")
        raise
    
    finally:
        # 关闭时清理
        logger.info("正在关闭量化投研系统...")
        
        try:
            # 关闭数据管理器
            if hasattr(app.state, 'data_manager'):
                logger.info("🔍 检查DataManager.close方法...")
                if hasattr(app.state.data_manager, 'close'):
                    logger.info("✅ DataManager.close方法存在")
                    await app.state.data_manager.close()
                elif hasattr(app.state.data_manager, 'cleanup'):
                    logger.info("⚠️ DataManager.close方法不存在，使用cleanup方法")
                    await app.state.data_manager.cleanup()
                else:
                    logger.error("❌ DataManager既没有close也没有cleanup方法")
                logger.info("数据管理器已关闭")
            
            # 关闭工作流管理器
            if hasattr(app.state, 'workflow_manager'):
                logger.info("🔍 检查WorkflowManager.close方法...")
                if hasattr(app.state.workflow_manager, 'close'):
                    logger.info("✅ WorkflowManager.close方法存在")
                    await app.state.workflow_manager.close()
                elif hasattr(app.state.workflow_manager, 'stop'):
                    logger.info("⚠️ WorkflowManager.close方法不存在，使用stop方法")
                    await app.state.workflow_manager.stop()
                else:
                    logger.error("❌ WorkflowManager既没有close也没有stop方法")
                logger.info("工作流管理器已关闭")
            
            # 关闭协调引擎
            if hasattr(app.state, 'coordination_engine'):
                logger.info("🔍 检查CoordinationEngine.close方法...")
                if hasattr(app.state.coordination_engine, 'close'):
                    logger.info("✅ CoordinationEngine.close方法存在")
                    await app.state.coordination_engine.close()
                elif hasattr(app.state.coordination_engine, 'shutdown'):
                    logger.info("⚠️ CoordinationEngine.close方法不存在，使用shutdown方法")
                    await app.state.coordination_engine.shutdown()
                else:
                    logger.error("❌ CoordinationEngine既没有close也没有shutdown方法")
                logger.info("协调引擎已关闭")
            
            # 关闭智能体系统
            if hasattr(app.state, 'agent_registry'):
                logger.info("🔍 检查AgentRegistry.close方法...")
                if hasattr(app.state.agent_registry, 'close'):
                    logger.info("✅ AgentRegistry.close方法存在")
                    await app.state.agent_registry.close()
                else:
                    logger.error("❌ AgentRegistry.close方法不存在")
                    logger.info("AgentRegistry没有标准的关闭方法，跳过清理")
                logger.info("智能体系统已关闭")
            
            # 关闭Redis
            await close_redis()
            logger.info("Redis连接已关闭")
            
            # 关闭数据库
            await close_database()
            logger.info("数据库连接已关闭")
            
        except Exception as e:
            logger.error(f"系统关闭时出错: {e}")
        
        logger.info("量化投研系统已关闭")


def create_app() -> FastAPI:
    """
    创建FastAPI应用实例
    
    Returns:
        FastAPI应用实例
    """
    settings = get_settings()
    
    # 创建FastAPI应用
    app = FastAPI(
        title="量化投研系统",
        description="基于多智能体的量化投资研究系统",
        version="1.0.0",
        docs_url="/docs" if settings.debug else None,
        redoc_url="/redoc" if settings.debug else None,
        lifespan=lifespan
    )
    
    # 设置中间件
    setup_middleware(app)
    
    # 设置依赖注入
    setup_dependencies(app)
    
    # 注册路由
    app.include_router(api_router, prefix="/api/v1")
    
    # 全局异常处理器
    @app.exception_handler(HTTPException)
    async def http_exception_handler(request: Request, exc: HTTPException):
        """HTTP异常处理器"""
        return JSONResponse(
            status_code=exc.status_code,
            content={
                "error": {
                    "code": exc.status_code,
                    "message": exc.detail,
                    "type": "HTTPException"
                }
            }
        )
    
    @app.exception_handler(Exception)
    async def general_exception_handler(request: Request, exc: Exception):
        """通用异常处理器"""
        logger.error(f"未处理的异常: {exc}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={
                "error": {
                    "code": 500,
                    "message": "内部服务器错误",
                    "type": "InternalServerError"
                }
            }
        )
    
    # 健康检查端点
    @app.get("/health")
    async def health_check():
        """健康检查"""
        return {
            "status": "healthy",
            "timestamp": "2024-01-01T00:00:00Z",
            "version": "1.0.0",
            "services": {
                "database": "connected",
                "redis": "connected",
                "agents": "running",
                "workflows": "running"
            }
        }
    
    # 系统信息端点
    @app.get("/info")
    async def system_info():
        """系统信息"""
        return {
            "name": "量化投研系统",
            "version": "1.0.0",
            "description": "基于多智能体的量化投资研究系统",
            "features": [
                "多智能体协作",
                "工作流编排",
                "数据管理",
                "实时分析",
                "风险控制"
            ],
            "architecture": {
                "layers": ["战略决策层", "管理执行层", "专业操作层"],
                "agents": 25,
                "coordination_modes": 5,
                "workflow_types": 4
            }
        }
    
    return app


# 创建应用实例
app = create_app()


if __name__ == "__main__":
    """直接运行应用"""
    settings = get_settings()
    
    uvicorn.run(
        "aiquant.main:app",
        host=settings.api_host,
        port=settings.api_port,
        reload=settings.debug,
        log_level="info" if settings.debug else "warning"
    )